const { connection } = require("../base/connect");
const { throwError } = require("../base/error");
const { sendData } = require("../base/success");
module.exports = async (ctx) => {
  const collection = (await connection).collection("foreign");
  // 获取州和国家的参数
  const continent = ctx.query.continent;
  const country = ctx.query.country;
  let result = new Array();
  let temp = new Array();
  // console.log("输出传入参数：", continent, country);
  // 用户没有传入参数,默认获取所有数据
  if (!continent && !country) {
    result = await collection
      .find(
        {},
        { projection: { _id: 0, provinceName: 1, currentConfirmedCount: 1 } }
      )
      .toArray();
  } else if (continent && !country) {
    //只有州 获取该州所有国家数据
    result = await collection
      .find(
        { continents: continent },
        { projection: { _id: 0, provinceName: 1, currentConfirmedCount: 1 } }
      )
      .toArray();
    if (!result.length) {
      throwError(ctx, 0, "地区不存在~");
      return;
    }
  } else if (!continent && country) {
    //只有国家 获取国家数据
    result = await collection
      .find(
        { provinceName: country },
        { projection: { _id: 0, provinceName: 1, currentConfirmedCount: 1 } }
      )
      .toArray();
    if (!result.length) {
      throwError(ctx, 0, "地区不存在~");
      return;
    }
  } else {
    //州和国家 获取所有数据
    result = await collection
      .find(
        { continents: continent, provinceName: country },
        { projection: { _id: 0, provinceName: 1, currentConfirmedCount: 1 } }
      )
      .toArray();
    if (!result.length) {
      throwError(ctx, 0, "地区不存在~");
      return;
    }
  }
  //重构目标数据
  result.forEach((item, index) => {
    temp.push({
      name: item.provinceName,
      value: item.currentConfirmedCount,
    });
  });
  sendData(ctx, temp);
};
